<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/7
 * Time: 17:37
 */

namespace App\Api\Admin\Controllers;

use App\Exceptions\ApiException;
use App\Models\Admin\Log;
use App\Models\Admin\Permission;
use App\Models\Admin\Role;
use App\Models\AdminUser;
use App\Services\Admin;
use Illuminate\Http\Request;
use App\Models\AdminMenu;

class AdminController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 角色列表
     * @return array
     */
    public function roleList()
    {
        $roles = Role::orderBy('id','asc')->get(['id','name',])->toArray();
       /* foreach ($roles as &$role) {
            if ($role['permissions'] === '*') {
                $permissions = Permission::get(['name', 'name_zh']);
            } else {
                $permissions = Permission::whereIn('id', explode(',', $role['permissions']))->get(['name', 'name_zh']);
            }

          $role['permissions'] = Admin::parsePermissions($permissions);
        }
        unset($role);*/
        return json_success('ok', $roles);
    }

    /**
     * @return array
     * 角色添加
     */
    public function AddRole(){
        $name = IT('name',true,'请输入角色名称');
        $check_name=  Role::where('name',$name)->first();
        if($check_name){
           return json_error('名称已存在');
        }
        $check_name=[
            'name'=>$name,
            'created_at'=>time2date(),
        ];
        $add_name = Role::insert($check_name);
        if($add_name){
           (new Log)->add($this->user,'添加了角色名称为-'.$name);
            return json_success('添加成功');
        }else{
            return json_error('添加失败 ');
        }
    }

    /**
     * 编辑角色及权限
     * @param Request $request
     * @return array
     */
    public function editRolePermission(Request $request)
    {
        $role_id = IT('role_id', true, '请选择需要编辑的角色');
        $ids = IT('ids', true, '请选择对应的权限');
        $ids = array_unique($ids);   // 去重
        if(!Role::find($role_id)) {
            return json_error('该角色数据异常');
        }
        $menu_count = AdminMenu::select(['id'])->whereIn('id', $ids)->count();
        if(count($ids) != $menu_count) {
            return json_error('存在异常的权限');
        }
        $ids = $this->parseIds($ids);
        $rs = Role::where('id', $role_id)->update(['permissions' => $ids, 'updated_at' => time2date()]);
        if(!$rs) {
            return json_error('数据保存异常');
        }
        (new Log)->add($this->user, '将权限修改为'.$ids);
        return json_success('ok');
    }

    /**
     * @desc 获取角色明细
     * @return array
     */
    public function getRoleDetails()
    {
        $role_id = IT('role_id', true, '请选择需要查询的角色');
        $fields = ['id', 'name', 'permissions'];
        $role_info = Role::select($fields)->where('id', $role_id)->first();
        if(!$role_info) {
            return json_error('角色数据异常');
        }

        if($role_info->permissions) {
            $permissions_list = explode(',', $role_info->permissions);
            foreach($permissions_list as &$permissions) {
                $permissions = (int)$permissions;
            }
        } else {
            $permissions_list = [];
        }

        return json_success('ok', ['id' => $role_info->id, 'name' => $role_info->name, 'permissions' => $permissions_list]);
    }

    /**
     * 日志列表
     * @param Request $request
     * @return array
     */
    public function log(Request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $username = empty($request->input('username')) ? '' : $request->input('username');
        $startdate = empty(IT('startdate')) ? '' : IT('startdate'); //开始时间
        $enddate = empty(IT('enddate')) ? '': IT('enddate'); //结束时间
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        if($enddate < $startdate){
            return json_error('结束时间要大于开始时间');
        }
        if($startdate == 'Invalid date'){
            $startdate = '';
        }
        if($enddate == 'Invalid date'){
            $enddate ='';
        }
        $fields = ['id', 'username', 'action', 'create_at'];
        $offset = ($page - 1) * $pagesize;
        $logs = Log::where(function($query) use($username,$startdate,$enddate) {
                if(!empty($username)){
                    $query->where('username','like','%'.$username. '%');
                }else if(!empty($startdate) && !empty($enddate) ) {
                    $query->whereBetween('create_at',[$startdate, $enddate]);
                }
            })->orderBy('id','desc')->take($pagesize)->skip($offset)->get($fields);
        $total = Log::where(function($query) use($username,$startdate,$enddate) {
                if(!empty($username)){
                    $query->where('username','like','%'.$username. '%');
                }else if(!empty($startdate) && !empty($enddate) ) {
                    $query->whereBetween('create_at',[$startdate, $enddate]);
                }})->count();
        $totalPage = ceil($total / $pagesize);
        $logs = $logs ?: [];
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $logs]);
    }

    /**
     * 转化id，去重
     * @param string $ids
     * @return array
     */
    private function checkIds($ids = '')
    {
        $ids = explode(',', $ids);
        foreach ($ids as &$id) {
            $id = (int) $id;
        }
        return array_unique($ids);
    }
    /**
     * 格式化权限id
     * @param $permissions
     * @return null|string
     */
    private function parseIds( $ids = [])
    {
        return implode(',', $ids);
    }
}